<template>
  <div class="relationship">
    <ContentWrap>
      <el-form ref="ruleFormRef" :rules="rules" :inline="true" :model="ruleForm" class="demo-form-inline search">
        <el-form-item label="关系名称" prop="relationName">
          <el-input v-model="ruleForm.relationName" placeholder="请输入关系名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSearch(ruleFormRef)" :icon="Search">搜索</el-button>
          <el-button @click="handleReset(ruleFormRef)" :icon="Refresh">重置</el-button>
          <el-button @click="handleAdd('add')" :icon="Plus" plain type="primary">添加</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div style="height: 560px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2 :columns="columns" :data="tableModule.tableData" :width="width" :height="height" fixed />
          </template>
        </el-auto-resizer>
      </div>
      <el-pagination :current-page="tableModule.currentPage" :page-size="tableModule.pageSize"
        :page-sizes="[10, 20, 30, 50]" background layout="total, sizes, prev, pager, next, jumper"
        :total="tableModule.count" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </ContentWrap>
    <!-- 添加编辑对话框 -->
    <addEditingDialog ref="addEditingDialogRef" @subEvent="getTableData" :dialogTitle="dialogTitle"
      :operationType="operationType" :currentOperationData="currentOperationData">
    </addEditingDialog>
  </div>
</template>
<script lang="tsx" setup>
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElTooltip } from 'element-plus'
import type { FormInstance, FormRules, Column } from 'element-plus'
import dayjs from 'dayjs'
import * as FormApi from '@/api/knowledge/relationship'
import addEditingDialog from './addEditingDialog.vue'

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  region: [{ required: true, message: '请选择所属图谱', trigger: 'change' }],
  name: [{ required: true, message: '请输入节点名称', trigger: 'blur' }]
})
interface RuleForm {
  name: string
  region: string
}
const ruleForm = reactive<RuleForm>({
  region: '',
  name: ''
})
const addEditingDialogRef = ref()
const dialogTitle = ref<string>('')  // 当前标题
const operationType = ref<string>('') // 当前操作类型（新增或编辑）
const currentOperationData = reactive({}) // 当前操作数据
// 表格数据
const tableModule = reactive({
  tableData: [], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})

onMounted(() => {
  getTableData()
})
// 重置
const handleReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getTableData()
  ElMessage({
    message: '重置成功',
    grouping: true,
    showClose: true,
    type: 'success'
  })
}
// 分页：pageSize 改变时会触发
const handleSizeChange = (val: number) => {
  tableModule.pageSize = val
  getTableData()
}

// 分页：currentPage 改变时会触发
const handleCurrentChange = (val: number) => {
  tableModule.currentPage = val
  getTableData()
}

const handleSearch = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) getTableData()
    else console.log('error submit!', fields)
  })
}
const getTableData = () => {
  return new Promise((resolve, reject) => {
    try {
      const params = {
        relationName: ruleForm.relationName,
        pageNo: tableModule.currentPage,
        pageSize: tableModule.pageSize
      }
      FormApi.getGraphRelationPage(params).then((res) => {
        tableModule.tableData = res.list
        tableModule.count = res.total
        resolve(res)
      })
    } catch {
      reject()
    } finally {
      console.log('getTableData')
      console.log('Promise执行完毕')
    }
  })
}
// 添加
const handleAdd = (handleType: string) => {
  dialogTitle.value = '添加关系维护'
  operationType.value = handleType
  addEditingDialogRef.value.open()
}
// 修改
const handleEdit = (handleType: string, data) => {
  dialogTitle.value = '修改关系维护'
  operationType.value = handleType
  Object.assign(currentOperationData, data.rowData)
  addEditingDialogRef.value.open()
}
// 删除
const deleteFcn = (data: any) => {
  ElMessageBox.confirm('确定永久删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(data.rowData.id)
      FormApi.deleteHybaseGraphRelation(data.rowData.id)
        .then((res: any) => {
          ElMessage({
            type: 'success',
            grouping: true,
            showClose: true,
            message: '删除已完成'
          })
          getTableData()
        })
        .catch((error: any) => {
          ElMessage({
            message: error,
            grouping: true,
            showClose: true,
            type: 'error'
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        grouping: true,
        showClose: true,
        message: '删除已取消'
      })
    })
}

const columns: Column<object>[] = [
  {
    key: 'id',
    title: 'ID',
    dataKey: 'id',
    width: 300,
    align: 'center',
    cellRenderer: ({ cellData: id }) => <div>{id}</div>
  },
  {
    key: 'relationName',
    title: '关系名称',
    dataKey: 'relationName',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: relationName }) => <div>{relationName}</div>
  },
  {
    key: 'createTime',
    title: '创建时间',
    dataKey: 'createTime',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: createTime }) => (
      <ElTooltip content={dayjs(createTime).format('YYYY/MM/DD')}>
        {<span class="flex items-center">{dayjs(createTime).format('YYYY/MM/DD')}</span>}
      </ElTooltip>
    )
  },
  {
    key: 'operations',
    title: '操作',
    cellRenderer: (data) => (
      <>
        <el-button onClick={handleEdit.bind(this, 'edit', data)} type="success" size="small">
          修改
        </el-button>
        <el-button onClick={deleteFcn.bind(this, data)} type="danger" size="small">
          删除
        </el-button>
      </>
    ),
    width: 230,
    align: 'center'
  }
]
</script>
<style lang="scss" scoped>
.relationship {
  .search {
    .el-form-item {
      margin: 0 32px 0 0;
    }
  }
}

.demo-form-inline .el-input {
  --el-input-width: 230px;
}

.demo-form-inline .el-select {
  --el-select-width: 230px;
}
</style>
